/**
 *
 */
package com.itboye.mengwu.app;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.server.ByService;
import com.itboye.core.utils.DebugLog;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.mymeng.MegActivity;
import com.itboye.mengwu.app.ui.mymeng.MyOrderActivity;
import com.itboye.mengwu.app.ui.mymeng.personsettings.ActivitySiXinXiangQing;
import com.itboye.mengwu.main.MainActivity;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;

/**
 * @author hebidu
 */
public class MainApplication extends Application {

    public static Context context;

    private static RequestQueue queue;

    private static MainApplication getInstance;

    public static MainApplication getGetInstance() {
        return getInstance;
    }

    JSONObject jsonObject;

    protected int type;

    protected String uid;

    protected String nickName;

    public MainActivity mainUI;

    public List<WeakReference<Activity>> activityList = new LinkedList<>();

    public void initImageLoader() {
        long maxMamory = Runtime.getRuntime().maxMemory();// 应用程序程序运行时所使用最大内存数
        maxMamory = (long) (maxMamory * 0.7);
        int v = Runtime.getRuntime().availableProcessors();
        int availableProcessors = v < 4 ? 3 : v - 1;

        // System.out.println("maxMamory : " + maxMamory +
        // "  availableProcessors: " + availableProcessors);

        // DebugToast.show("maxMamory : " + (maxMamory/1024.0f/1024 )+
        // "  availableProcessors: " + availableProcessors, 1);

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // 设置图片下载期间显示的图片
                .showImageOnLoading(R.drawable.default_image)
                .showImageForEmptyUri(R.drawable.default_image)// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.default_image) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                .bitmapConfig(Config.RGB_565)
                // .displayer(new RoundedBitmapDisplayer(20))// 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象 

        // File cacheDir = StorageUtils.getOwnCacheDirectory(App.ctx,
        // "sunsun/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getInstance)
                .memoryCacheExtraOptions(480, 800)
                // max width, max
                // height，即保存的每个缓存文件的最大长宽
                // .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75,
                // null) // Can slow ImageLoader, use it carefully (Better don't
                // use it)/设置缓存的详细信息，最好不要设置这个
                .threadPoolSize(availableProcessors)
                // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                // .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 *
                // 1024)) // You can pass your own memory cache
                // implementation/你可以通过自己的内存缓存实现
                // .memoryCache(new WeakMemoryCache())

                .memoryCacheSize((int) maxMamory)
                // .memoryCacheSize(15 * 1024 * 1024)

                .diskCacheSize(80 * 1024 * 1024)
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
                // 加密

                .tasksProcessingOrder(QueueProcessingType.LIFO) // 后进先出
                // .diskCacheFileCount(100) //缓存的文件数量
                // .diskCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
                // .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .defaultDisplayImageOptions(options)
                // .imageDownloader(new BaseImageDownloader(App.ctx, 5 * 1000,
                // 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
                // .imageDownloader(new DownloadImageFromNetWork(App.ctx, 5 *
                // 1000, 30 * 1000)).writeDebugLogs() // Remove
                // for
                // release
                // app
                .build();// 开始构建
        // Initialize ImageLoader with configuration.

        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(
                config);// 全局初始化此配置

    }

    public static void setGetInstance(MainApplication getInstance) {
        MainApplication.getInstance = getInstance;
    }

    public void addActivity(Activity activity) {
        activityList.add(new WeakReference<Activity>(activity));
    }

    // 遍历所有Activity并finish
    public void exit() {
        for (WeakReference<Activity> activity : activityList) {
            if (activity.get() != null) {
                activity.get().finish();
            }

        }
//        System.exit(0);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getInstance = this;
        context = getApplicationContext();
        initImageLoader();
        Intent intent = new Intent(getApplicationContext(), ByService.class);
        // intent.putExtra("msg", "asdsdas");
        startService(intent);
        queue = Volley.newRequestQueue(context);
        initUMengPush();
        initSessionLogin();
    }

    int loopTimes = 2000;//五分钟

    private void initSessionLogin() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String login_session = SPUtils.get(getApplicationContext(), null, SpPublicParams.SESSION_CODE, "") + "";
                System.out.println("执行中--"+login_session);
                if (mainUI != null && !login_session.equals("")) {
                    mainUI.onLogin();
                }
                initSessionLogin();
            }
        }, loopTimes);
    }


    private void initUMengPush() {
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(true);
        System.out.println("" + "zhixing1");
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 参考集成文档的1.6.3 http://dev.umeng.com/push/android/integration#1_6_3
             * */
            @Override
            public void dealWithCustomMessage(final Context context,
                                              final UMessage msg) {
                super.dealWithCustomMessage(context, msg);
                System.out.println("dealWithCustomMessage is In ui thread? "
                        + (Looper.getMainLooper() == Looper.myLooper()));
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        System.out.println("" + "zhixing2");
                        // TODO Auto-generated method stub
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            System.out.println("msg+" + msg);
                            // 自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext())
                                    .trackMsgClick(msg);
                        } else {
                            System.out.println("" + "zhixing3");
                            // 自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext())
                                    .trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }

            @Override
            public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
                // TODO Auto-generated method stub
                super.dealWithNotificationMessage(arg0, arg1);
                System.out.println("执行了sssssssss2122");
                if (arg1.activity.equals("call_message")) {// 更新私信及私信列表界面
                    Intent intent = new Intent("privatemsg");
                    sendBroadcast(intent);
                }
                Intent intent2 = new Intent("change_img");
                sendBroadcast(intent2);
                System.out.println(">>>这是推送消息" + arg1.getRaw() + ":"
                        + arg1.extra.get("type"));
            }

            /**
             * 参考集成文档的1.6.4 http://dev.umeng.com/push/android/integration#1_6_4
             * */
            @Override
            public Notification getNotification(Context context, UMessage msg) {
                switch (msg.builder_id) {
                    case 1:
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                                context);
                        RemoteViews myNotificationView = new RemoteViews(
                                context.getPackageName(),
                                R.layout.notification_view);
                        myNotificationView.setTextViewText(R.id.notification_title,
                                msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text,
                                msg.text);
                        myNotificationView.setImageViewBitmap(
                                R.id.notification_large_icon,
                                getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(
                                R.id.notification_small_icon,
                                getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setContentTitle(msg.title)
                                .setSmallIcon(getSmallIconId(context, msg))
                                .setContentText(msg.text).setTicker(msg.ticker)
                                .setAutoCancel(true);
                        Notification mNotification = builder.build();
                        // 由于Android
                        // v4包的bug，在2.3及以下系统，Builder创建出来的Notification，并没有设置RemoteView，故需要添加此代码
                        mNotification.contentView = myNotificationView;
                        return mNotification;

                    default:
                        // 默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }

        };
        mPushAgent.setMessageHandler(messageHandler);

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                super.dealWithCustomAction(context, msg);
            }

            @Override
            public void openActivity(Context arg0, UMessage msg) {
                // TODO Auto-generated method stub
                // super.openActivity(arg0, msg);
                DebugLog.v("bytag", msg.activity);
                if (msg.activity.equals("bbs_message")) {
                    try {
                        jsonObject = msg.getRaw().getJSONObject("extra");
                        // jsonObject = jsonObject.getJSONObject("after_open");
                        type = jsonObject.getInt("type");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    // Intent intent = new Intent(MainApplication.context,
                    // .class);
                    // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    // if (type == 0) {
                    // SPUtils.put(App.ctx, null, SPContants.IS_READ_ONE,
                    // false);
                    // intent.putExtra("current", 3);
                    // } else if (type == 1) {
                    // SPUtils.put(App.ctx, null, SPContants.IS_READ_TWO,
                    // false);
                    // intent.putExtra("current", 4);
                    // }
                    // startActivity(intent);
                } else if (msg.activity.equals("order_message")) {
                    // try {
                    // jsonObject = msg.getRaw().getJSONObject("extra");
                    // jsonObject = jsonObject.getJSONObject("after_open");
                    // order_code = jsonObject.getString("order_code");
                    // } catch (JSONException e) {
                    // // TODO Auto-generated catch block
                    // e.printStackTrace();
                    // }
                    Intent intent = new Intent(getApplicationContext(),
                            MyOrderActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    // String url =
                    // "http://sunsun.itboye.com/index.php/Webview/Express/viewOrder?order_code="
                    // + order_code;
                    // System.out
                    // .println("model.getExtra().getafterOpen().getOrderCode()"
                    // + order_code);
                    startActivity(intent);

                } else if (msg.activity.equals("system_message")) {
                    // try {
                    // jsonObject = msg.getRaw().getJSONObject("extra");
                    // jsonObject = jsonObject.getJSONObject("after_open");
                    // id = jsonObject.getString("id");
                    // } catch (JSONException e) {
                    // // TODO Auto-generated catch block
                    // e.printStackTrace();
                    // }
                    Intent intent = new Intent(getApplicationContext(),
                            MegActivity.class);// 消息
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } else if (msg.activity.equals("call_message")) {// 私信消息
                    DebugLog.v("bytag", "d" + msg.getRaw() + "");
                    try {
                        jsonObject = msg.getRaw().getJSONObject("extra");
                        uid = jsonObject.getString("uid");
                        nickName = jsonObject.getString("nickname");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    Intent intent = new Intent(getApplicationContext(),
                            ActivitySiXinXiangQing.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("rela_uid", uid);
                    intent.putExtra("to_nick", nickName);
                    startActivity(intent);

                }
            }
        };

        // 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        // 参考http://bbs.umeng.com/thread-11112-1-1.html
        // CustomNotificationHandler notificationClickHandler = new
        // CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        // if (MiPushRegistar.checkDevice(this)) {
        // MiPushRegistar.register(this, "2882303761517400865",
        // "5501740053865");
        // }

    }

    public static Context getContext() {

        return context;
    }

    /**
     * @return the queue
     */
    public static RequestQueue getQueue() {
        return queue;
    }

    public static <T> void addRequest(Request<T> request) {
        request.addMarker("itboye");
        getQueue().add(request);
    }

}
